<template>
    <el-dialog
        title="系统操作"
        width="460px"
        v-model="dialogVisible"
        :before-close="handleCancel"
    >
        <el-tabs
            v-model="activeName"
            class="tabs"
            @tab-click="tabHandleClick(activeName === 'accountInfo' ? accountInfoRef : changePwdRef)"
        >
            <!-- 账户信息 -->
            <el-tab-pane label="账户信息" name="accountInfo">
                <!-- 系统 logo -->
                <div class="flex-items-box w-full p-20 flex-col justify-center">
                    <div class="system-img-box mb-20 flex-center-box rounded-full">
                        <el-upload
                            :action="uploadImgURL"
                            :auto-upload="true"
                            :show-file-list="false"
                            :on-success="uploadSuccess"
                        >
                            <template #default>
                                <el-avatar
                                    :size="120"
                                    fit="contain"
                                    shape="square"
                                    :src="accountInfoForm.systemImgUrl"
                                />
                            </template>
                        </el-upload>
                    </div>
                    <p class="text-12"><i class="text-warning">* </i>建议上传 400* 400 且大小不超过 2M 的图片</p>
                </div>
                <!-- 表单 -->
                <el-form
                    ref="accountInfoRef"
                    :model="accountInfoForm"
                    :rules="accountInfoRules"
                    :disabled="!isEdit"
                    label-width="120px"
                    status-icon
                >
                    <el-form-item label="登录账号:">
                        <span>{{ accountInfoForm.username }}</span>
                    </el-form-item>
                    <el-form-item label="管理员名称:" prop="adminName">
                        <template v-if="isEdit">
                            <el-input v-model="accountInfoForm.adminName" />
                        </template>
                        <template v-else>
                            <span>{{ accountInfoForm.adminName }}</span>
                        </template>
                    </el-form-item>
                    <el-form-item label="管理员手机号:" prop="adminPhone">
                        <template v-if="isEdit">
                            <el-input v-model="accountInfoForm.adminPhone" />
                        </template>
                        <template v-else>
                            <span>{{ accountInfoForm.adminPhone }}</span>
                        </template>
                    </el-form-item>
                    <el-form-item label="公司主体:" prop="companyEntity">
                        <template v-if="isEdit">
                            <el-input v-model="accountInfoForm.companyEntity" />
                        </template>
                        <template v-else>
                            <span>{{ accountInfoForm.companyEntity }}</span>
                        </template>
                    </el-form-item>
                </el-form>
                <!-- 可执行操作 -->
                <div class="mb-20 flex flex-center-box">
                    <el-button @click="handleCancel" round>取消</el-button>
                    <el-button type="primary" @click="handleOperation" round>{{ isEdit ? '保存' : '编辑' }}</el-button>
                </div>
            </el-tab-pane>
            <!-- 修改密码 -->
            <el-tab-pane label="修改密码" name="changePwd">
                <!-- 表单 -->
                <el-form
                    ref="changePwdRef"
                    :model="changePwdForm"
                    :rules="changePwdRules"
                    label-width="100px"
                    status-icon
                >
                    <el-form-item label="原密码" prop="oldPwd">
                        <el-input
                            placeholder="请输入"
                            type="password"
                            v-model="changePwdForm.oldPwd"
                        />
                    </el-form-item>
                    <el-form-item label="新密码" prop="newPwd">
                        <el-input
                            placeholder="请输入"
                            type="password"
                            v-model="changePwdForm.newPwd"
                        />
                    </el-form-item>
                    <el-form-item label="确认新密码" prop="surePwd">
                        <el-input
                            placeholder="请输入"
                            type="password"
                            v-model="changePwdForm.surePwd"
                        />
                    </el-form-item>
                </el-form>
                <!-- 操作 -->
                <div class="mb-20 flex flex-center-box">
                    <el-button @click="handleCancel" round>取消</el-button>
                    <el-button type="primary" @click="submitForm(changePwdRef)" round>保存</el-button>
                </div>
            </el-tab-pane>
        </el-tabs>
    </el-dialog>
</template>

<script setup lang="ts">
import { computed, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import type { FormInstance, FormRules } from 'element-plus'
import { httpAccountInfo, httpChangePwd, SystemInfo } from '@api/module/system'
import { HttpResponse } from '@api/http'
import { uploadImgURL } from '@/config'
import { ElMessages, FormRule, GlobalMitt, Storage, timeout } from '@utils/methods'

const router = useRouter()

// 系统信息
const systemInfo = Storage.get('systemInfo')

/**
 * 组件
 * */
// 组件传参
const props = defineProps({
    // 显示隐藏
    modelValue: {
        type: Boolean,
        default: false
    }
})
// 父组件方法
const emit = defineEmits(['update:modelValue'])

/**
 * 选项卡
 * */
// 激活的选项卡
const activeName = ref('accountInfo')
// 是否编辑
const isEdit = ref(false)
/**
 * 选项卡切换
 * */
const tabHandleClick = (formEl: FormInstance | undefined) => {
    // 重置表单
    formEl?.resetFields()
    // 退出账户信息编辑
    isEdit.value = false
}

/**
 * 弹窗
 * */
// 弹窗显示隐藏
const dialogVisible = computed(() => props.modelValue)
/**
 * 弹窗关闭
 * */
const handleClose = async () => {
    // 更新父组件数据，关闭弹窗
    emit('update:modelValue', false)
    await timeout(300)
    // 重置选项卡
    activeName.value = 'accountInfo'
}

/**
 * 账户信息
 * */
// 表单实例
const accountInfoRef = ref<FormInstance>()

// 表单数据
const accountInfoForm = ref<SystemInfo | null>(null)

/**
 * 刷新 systemInfo 信息
 * */
const refreshSystemInfo = () => {
    accountInfoForm.value = Storage.get('systemInfo')
}

refreshSystemInfo()

// 校验信息
const accountInfoRules = reactive<FormRules>({
    adminName: [
        FormRule.requireRule('请输入管理员名称'),
        FormRule.lengthRule(2, 10, '长度在 2-10 个字符')
    ],
    adminPhone: [
        FormRule.requireRule('请输入管理员手机号'),
        FormRule.lengthRule(11, 11, '请输入正确的手机号')
    ],
    companyEntity: [
        FormRule.requireRule('请输入公司主体'),
        FormRule.lengthRule(5, 30, '长度在 5-30 个字符')
    ]
})

/**
 * 更新信息
 * */
const submitAccountInfo = () => {
    const { adminName, adminPhone, companyEntity } = <SystemInfo>accountInfoForm.value
    const params = {
        id: systemInfo.id,
        adminName,
        adminPhone,
        companyEntity
    }
    // 更新信息
    httpAccountInfo(params).then(({ success, message }) => {
        if (success) {
            // 退出编辑
            isEdit.value = false
            // 更新修改后的新信息
            delete params.id
            Storage.update('systemInfo', params)
            // 刷新 header 信息
            GlobalMitt.emit('refreshSystemInfo')
            // 关闭弹窗
            emit('update:modelValue', false)
            ElMessages.success('修改成功！')
        } else {
            ElMessages.warning(message!)
        }
    })
}

/**
 * 头像上传成功
 * */
const uploadSuccess = ({ data: systemImgUrl }: HttpResponse) => {
    httpAccountInfo({
        id: systemInfo.id,
        systemImgUrl
    }).then(({ success }) => {
        if (success) {
            Storage.update('systemInfo', { systemImgUrl })
            GlobalMitt.emit('refreshSystemInfo')
            refreshSystemInfo()
            ElMessages.success('上传成功！')
        }
    })
}

/**
 * 修改密码
 * */
// 表单实例
const changePwdRef = ref<FormInstance>()

// 表单数据格式
interface ChangePwdForm {
    /** @description 原密码 */
    oldPwd: string
    /** @description 新密码 */
    newPwd: string
    /** @description 确认密码 */
    surePwd: string
}

// 表单数据
const changePwdForm = reactive<ChangePwdForm>({
    oldPwd: '',
    newPwd: '',
    surePwd: ''
})

// 校验两次新密码是否一致
const validatePwd = (rule: any, value: any, callback: any) => {
    if (value === '') {
        callback(new Error('请输入密码'))
    } else if (!/^[a-zA-Z][a-zA-Z0-9]{7,13}$/.test(value)) {
        callback(new Error('请输入由字母开头，数字和字母组成的 8-14 位密码!'))
    } else if (changePwdForm.surePwd !== changePwdForm.newPwd) {
        callback(new Error('两次密码输入不一致'))
    } else {
        callback()
    }
}

// 修改密码表单验证
const changePwdRules = reactive<FormRules>({
    oldPwd: [
        FormRule.requireRule('请输入原密码'),
        FormRule.lengthRule(6, 20, '长度在 6-20 个字符')
    ],
    newPwd: [
        FormRule.requireRule('请输入新密码'),
        { validator: validatePwd, trigger: 'blur' }
    ],
    surePwd: [
        FormRule.requireRule('请再次输入新密码'),
        { validator: validatePwd, trigger: 'blur' }
    ]
})

/**
 * 修改密码请求
 * */
const submitChangePwd = () => {
    const { oldPwd, newPwd } = changePwdForm
    httpChangePwd({
        id: systemInfo.id,
        oldPwd,
        newPwd
    }).then(({ success, message }) => {
        if (success) {
        // 关闭弹窗
            handleClose()
            // 退出登录
            Storage.clear()
            router.push('/login').then(async () => {
                await timeout(1000)
                ElMessages.common('请重新登录')
            })
        } else {
            ElMessages.warning(message!)
        }
    })
}

/**
 * 提交验证
 * */
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate(valid => {
        if (valid) {
            activeName.value === 'accountInfo' ? submitAccountInfo() : submitChangePwd()
        }
    })
}

/**
 * 取消按钮
 * */
const handleCancel = () => {
    if (activeName.value === 'accountInfo') {
        // 编辑模式 => 清除表单验证
        if (isEdit.value) {
            accountInfoRef.value?.resetFields()
            refreshSystemInfo()
            isEdit.value = !isEdit.value
        } else {
            // 非编辑模式关闭弹窗
            handleClose()
        }
    } else {
        changePwdRef.value?.resetFields()
        handleClose()
    }
}

/**
 * 账号信息 => 编辑或保存
 * */
const handleOperation = () => {
    if (isEdit.value) {
        submitForm(accountInfoRef.value)
        return
    }
    isEdit.value = !isEdit.value
}
</script>

<style lang="less" scoped>
.system-img-box{
    width: 130px;
    height: 130px;
}

.el-avatar{
    background: none;
}

.el-form{
    margin-top: 20px;
    width: 70%;
    margin-left: 15%;
}

.el-form-item{
    margin-bottom: 30px;
}
</style>
